package com.crape.common.servlet;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

public class ValidateCode extends HttpServlet {

	public static final String SESSION_ATTR_VALIDATION_CODE = "validateCode";

	private static final Logger logger = Logger.getLogger(ValidateCode.class);

	private static String CODETYPE = "checkcode";
	private static final long serialVersionUID = -5384211439529254585L;

	private static final ValidateCodeBean checkCode = new ValidateCodeBean();

	static {
		System.setProperty("java.awt.headless", "true");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		BufferedImage image;
		String type = request.getParameter("code");
		if (null != type && type.equals(CODETYPE)) {
			image = checkCode.get4Chars();
		} else {
			image = checkCode.get3Chars();
		}
		HttpSession session = request.getSession(true);
		session.setAttribute(SESSION_ATTR_VALIDATION_CODE,
				checkCode.getCodeString());
		response.setContentType("image/gif");
		if (logger.isDebugEnabled()) {
			logger.debug("Generating Validation Code:SID="
					+ request.getSession().getId() + "; Validation Code="
					+ checkCode.getCodeString());
		}
		ServletOutputStream imgOutput = null;
		try {
			imgOutput = response.getOutputStream();
			ImageIO.write(image, "JPEG", imgOutput);
			imgOutput.close();
		} catch (IOException e) {
			logger.warn(
					"Unable to write validation code into servlet output stream due to ",
					e);
		} finally {
			if (null != imgOutput) {
				imgOutput.close();
			}
		}
	}
}
